package com.homework.gateway.filter;

import com.homework.gateway.client.UserFeignClient;
import com.homework.util.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

@Component
//@AllArgsConstructor
public class TokenFilter implements GlobalFilter {
    protected static String[] ignoreUrl = {
        "/api/user/register", "/api/user/isRegistered", "/api/user/login",
            "/api/code/create", "/api/code/validate",
            "/api/email/send"
    };

    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        //不需要认证
        if(isIgnore(request)) {
            Mono<Void> result =  chain.filter(exchange);

            //如果是登录接口， 需要设置cookie
//            if(isLogin(request)) {
//                return chain.filter(exchange).then(Mono.fromRunnable(() -> {
//                    System.out.println("post filter...");
//
//                    ServerHttpResponse response = exchange.getResponse();
//                    ServerHttpResponseDecorator s = new ServerHttpResponseDecorator(response);
//                    List<String> mm = s.getHeaders().get("Set-Cookie");
//                    response.addCookie(ResponseCookie.from("spring_cloud_token", mm.get(0)).path("/").maxAge(Duration.ofDays(1)).build());
//                }));
//            }

            return result;
        }

        //获取token
        HttpCookie httpCookie = exchange.getRequest().getCookies().getFirst("spring_cloud_token");
        String token = null;
        if (null != httpCookie) {
            token = httpCookie.getValue();
        }

        //进行认证
        if(token != null && !isAuth( token)) { //
            ServerHttpResponse response  = exchange.getResponse();
            // 拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }

        return chain.filter(exchange);
    }

    protected boolean isIgnore(ServerHttpRequest request) {
        System.out.println(request.getPath());
        String path = request.getPath().toString();
        for (int i = 0; i < ignoreUrl.length; i++) {
            if( path.indexOf(ignoreUrl[i]) != -1 ) {
                return true;
            }
        }
        return false;
    }

    //判断是否是登录接口
    protected boolean isLogin(ServerHttpRequest request) {
        String path = request.getPath().toString();
        if(path.indexOf("/api/user/login") != -1) {
            return true;
        }

        return false;
    }

    protected boolean isAuth(String token) {
        ResultMsg msg = userFeignClient.info(token);
        if( msg.getData() == null ) {
            return false;
        }

        return true;
    }
}
